#include<bits/stdc++.h>
using namespace std;
int a[1010],b[1010];
bool hw(string s)
{
	for(int i=0;i<s.size();i++)
	{
		if(s[i]!=s[s.size()-i-1]) return 0;
	}
	return 1;
}
int main(){
	freopen("hw.in","r",stdin);
	freopen("hw.out","w",stdout);
	int n,m;
	cin>>m>>n;
	string s;
	cin>>s;
	if(hw(s))
	{
		cout<<"0";
		return 0;
	}
	for(int i=1;i<=m;i++)
	{
		char k;
		cin>>k;
		cin>>a[k]>>b[k];
	}
	if(n==2)
	{
		cout<<min(min(a[s[1]],a[s[0]]),min(b[s[1]],b[s[0]]));
	}
	return 0;
}

